<?php

namespace apiend\models;

use Yii;
use common\base\Model;
use common\logics\SmsCaptchaForm;
use apiend\models\User;
use common\models\user\UserMeta;
use yii\db\Exception;
use common\helpers\IpHelper;

/**
 * 用户注册
 * Signup form
 */
class SignupForm extends Model {

    public $mobile;
    public $code;
    public $password;

    //
    const PASSWORD_PATTERN = '/((?=.*[a-z])(?=.*\d)|(?=[a-z])(?=.*[#@!~%^&*])|(?=.*\d)(?=.*[#@!~%^&*]))[a-z\d#@!~%^&*]{6,16}/i';

    /**
     * @inheritdoc
     */
    public function rules() {
        return [
            [['mobile', 'code', 'password'], 'required'],
            ['mobile', 'string', 'min' => 11, 'max' => 11],
            ['code', 'string', 'min' => 4, 'max' => 4],
            ['password', 'string', 'min' => 6, 'max' => 16],
//            ['password', 'match', 'pattern' => self::PASSWORD_PATTERN, 'message' => '密码过于简单'],
            ['mobile', '\common\validators\MobileValidator'],
            ['mobile', 'validateUser'],
            ['code', 'validateCaptchaCode'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels() {
        return [
            'mobile' => '手机号',
            'code' => '短信验证码',
            'password' => '密码',
        ];
    }

    /**
     * Validates the password.
     * This method serves as the inline validation for password.
     *
     * @param string $attribute the attribute currently being validated
     * @param array $params the additional name-value pairs given in the rule
     */
    public function validateUser($attribute) {
        if (!$this->hasErrors()) {
            $user = User::findByMobile($this->$attribute);
            if ($user) {
                $this->addError($attribute, '该手机号已注册，您可以使用手机号直接登录');
            }
        }
    }

    /**
     * Validates the password.
     * This method serves as the inline validation for password.
     *
     * @param string $attribute the attribute currently being validated
     * @param array $params the additional name-value pairs given in the rule
     */
    public function validatePassword($attribute) {
        if (!$this->hasErrors()) {
            //@todo
            //密码强度校验
            $pa = '/^(?=(.*[A-Za-z]){2})(?=.*[0-9])[A-Za-z0-9@$#]{6,16}$/';
        }
    }

    /**
     * Validates the password.
     * This method serves as the inline validation for password.
     *
     * @param string $attribute the attribute currently being validated
     * @param array $params the additional name-value pairs given in the rule
     */
    public function validateCaptchaCode($attribute) {
        if (!$this->hasErrors() && YII_ENV_PROD) {
            $captcha = Yii::$app->cache->get('captcha_' . SmsCaptchaForm::SCOPE_REGISTER . '_' . $this->mobile);
            if ($captcha == false) {
                $this->addError($attribute, $this->getAttributeLabel($attribute) . '已过期');
            } elseif ($captcha !== $this->$attribute) {
                $this->addError($attribute, $this->getAttributeLabel($attribute) . '不正确');
            }
        }
    }

    /**
     * Signs user up.
     *
     * @return User|null the saved model or null if saving fails
     */
    public function signup() {
        if (!$this->validate()) {
            $this->dumpError('', $this->getFirstErrors());
        }

        $user = new User();
        $user->setUsernameByMobile($this->mobile);
        $user->setPassword($this->password);
        $user->generateAuthKey();

        $meta = new UserMeta();
        $meta->setMobile($this->mobile);
        $meta->avatar = '/attachments/avatar/default.jpg';
        $meta->ip = IpHelper::ip();

        $transaction = Yii::$app->db->beginTransaction();
        try {
            if (!$user->save()) {
                throw new Exception('账号信息创建失败');
            }
            $meta->id = $user->id;
            if (!$meta->save()) {
                throw new Exception('用户基本信息保存失败');
            }
            $transaction->commit();
        } catch (Exception $e) {
            $transaction->rollBack();
            $this->dumpError('', $e);
        }

        Yii::$app->cache->delete('captcha_' . SmsCaptchaForm::SCOPE_REGISTER . '_' . $this->mobile);

        return $user->meta;
    }

}
